package com.isseiaoki.simplecropview.util;

import ohos.aafwk.content.Intent;
import ohos.agp.utils.Matrix;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.utils.net.Uri;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


@SuppressWarnings("unused")
public class Utils {
    private static final String TAG = Utils.class.getSimpleName();
    private static final int SIZE_DEFAULT = 2048;
    private static final int SIZE_LIMIT = 4096;
    public static int sInputImageWidth = 0;
    public static int sInputImageHeight = 0;


    public static void copyExifInfo(Context context, Uri sourceUri, Uri saveUri, int outputWidth,
                                    int outputHeight) {
        if (sourceUri == null || saveUri == null) return;
        try {
            File sourceFile = Utils.getFileFromUri(context, sourceUri);
            File saveFile = Utils.getFileFromUri(context, saveUri);
            if (sourceFile == null || saveFile == null) {
                return;
            }
            String sourcePath = sourceFile.getCanonicalPath();
            String savePath = saveFile.getCanonicalPath();

            ExifInterface sourceExif = new ExifInterface(sourcePath);
            List<String> tags = new ArrayList<>();
            tags.add(ExifInterface.TAG_DATETIME);
            tags.add(ExifInterface.TAG_FLASH);
            tags.add(ExifInterface.TAG_FOCAL_LENGTH);
            tags.add(ExifInterface.TAG_GPS_ALTITUDE);
            tags.add(ExifInterface.TAG_GPS_ALTITUDE_REF);
            tags.add(ExifInterface.TAG_GPS_DATESTAMP);
            tags.add(ExifInterface.TAG_GPS_LATITUDE);
            tags.add(ExifInterface.TAG_GPS_LATITUDE_REF);
            tags.add(ExifInterface.TAG_GPS_LONGITUDE);
            tags.add(ExifInterface.TAG_GPS_LONGITUDE_REF);
            tags.add(ExifInterface.TAG_GPS_PROCESSING_METHOD);
            tags.add(ExifInterface.TAG_GPS_TIMESTAMP);
            tags.add(ExifInterface.TAG_MAKE);
            tags.add(ExifInterface.TAG_MODEL);
            tags.add(ExifInterface.TAG_WHITE_BALANCE);

            tags.add(ExifInterface.TAG_EXPOSURE_TIME);
            tags.add(ExifInterface.TAG_APERTURE);
            tags.add(ExifInterface.TAG_ISO);

            tags.add(ExifInterface.TAG_DATETIME_DIGITIZED);
            tags.add(ExifInterface.TAG_SUBSEC_TIME);
            tags.add(ExifInterface.TAG_SUBSEC_TIME_DIG);
            tags.add(ExifInterface.TAG_SUBSEC_TIME_ORIG);

            tags.add(ExifInterface.TAG_F_NUMBER);
            tags.add(ExifInterface.TAG_ISO_SPEED_RATINGS);
            tags.add(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED);
            tags.add(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL);
//            }

            ExifInterface saveExif = new ExifInterface(savePath);
            String value;
            for (String tag : tags) {
                value = sourceExif.getAttribute(tag);
                if (!TextUtils.isEmpty(value)) {
                    saveExif.setAttribute(tag, value);
                }
            }
            saveExif.setAttribute(ExifInterface.TAG_IMAGE_WIDTH, String.valueOf(outputWidth));
            saveExif.setAttribute(ExifInterface.TAG_IMAGE_LENGTH, String.valueOf(outputHeight));
            saveExif.setAttribute(ExifInterface.TAG_ORIENTATION,
                    String.valueOf(ExifInterface.ORIENTATION_UNDEFINED));

            saveExif.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static int getExifRotation(File file) {
        if (file == null) return 0;
        try {
            ExifInterface exif = new ExifInterface(file.getCanonicalPath());
            return getRotateDegreeFromOrientation(
                    exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED));
        } catch (IOException e) {
            Logger.e("An error occurred while getting the exif data: " + e.getMessage(), e);
        }
        return 0;
    }

    public static int getExifRotation(Context context, Uri uri) {
        return 0;
    }

    public static int getExifOrientation(Context context, Uri uri) {
        String authority = uri.getDecodedAuthority().toLowerCase();
        int orientation;
        if (authority.endsWith("media")) {
            orientation = getExifRotation(context, uri);
        } else {
            orientation = getExifRotation(getFileFromUri(context, uri));
        }
        return orientation;
    }

    public static int getRotateDegreeFromOrientation(int orientation) {
        int degree = 0;
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                degree = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                degree = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                degree = 270;
                break;
            default:
                break;
        }
        return degree;
    }

    public static Matrix getMatrixFromExifOrientation(int orientation) {
        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_UNDEFINED:
                break;
            case ExifInterface.ORIENTATION_NORMAL:
                break;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.postScale(-1.0f, 1.0f);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.postRotate(180.0f);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.postScale(1.0f, -1.0f);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.postRotate(90.0f);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.postRotate(-90.0f);
                matrix.postScale(1.0f, -1.0f);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.postRotate(90.0f);
                matrix.postScale(1.0f, -1.0f);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.postRotate(-90.0f);
                break;
        }
        return matrix;
    }

    public static int getExifOrientationFromAngle(int angle) {
        int normalizedAngle = angle % 360;
        switch (normalizedAngle) {
            case 0:
                return ExifInterface.ORIENTATION_NORMAL;
            case 90:
                return ExifInterface.ORIENTATION_ROTATE_90;
            case 180:
                return ExifInterface.ORIENTATION_ROTATE_180;
            case 270:
                return ExifInterface.ORIENTATION_ROTATE_270;
            default:
                return ExifInterface.ORIENTATION_NORMAL;
        }
    }

    public static Uri ensureUriPermission(Context context, Intent intent) {
        Uri uri = intent.getUri();
        final int takeFlags = intent.getFlags();
        return uri;
    }


    public static File getFileFromUri(final Context context,
                                      final Uri uri) {
        return null;
    }

    public static class RawDocumentsHelper {
        public static final String RAW_PREFIX = "raw:";

        public static boolean isRawDocId(String docId) {
            return docId != null && docId.startsWith(RAW_PREFIX);
        }

        public static String getDocIdForFile(File file) {
            try {
                return RAW_PREFIX + file.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        public static String getAbsoluteFilePath(String rawDocumentId) {
            return rawDocumentId.substring(RAW_PREFIX.length());
        }
    }


    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {
        return null;
    }


    public static PixelMap decodeSampledBitmapFromUri(Context context, Uri sourceUri, int requestSize) {
        InputStream stream = null;
        PixelMap bitmap = null;
        File file = new File(sourceUri.getDecodedPath());
        boolean issss = file.exists();
        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
        sourceOptions.formatHint = "image/jpeg";
        ImageSource imageSource = null;
        ImageSource.DecodingOptions decodingOptions = null;
        try {
            imageSource = ImageSource.create(file, sourceOptions);
            decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.sampleSize = 1;
            decodingOptions.desiredSize = new Size(DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().width, DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes().height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageSource.createPixelmap(decodingOptions);
    }

    public static int calculateInSampleSize(Context context, Uri sourceUri, int requestSize) {
        InputStream is = null;
        int inSampleSize = 1;
        return inSampleSize;
    }

    public static PixelMap getScaledBitmapForHeight(PixelMap bitmap, int outHeight) {
        float currentWidth = bitmap.getImageInfo().size.width;
        float currentHeight = bitmap.getImageInfo().size.height;
        float ratio = currentWidth / currentHeight;
        int outWidth = Math.round(outHeight * ratio);
        return getScaledBitmap(bitmap, outWidth, outHeight);
    }

    public static PixelMap getScaledBitmapForWidth(PixelMap bitmap, int outWidth) {
        float currentWidth = bitmap.getImageInfo().size.width;
        float currentHeight = bitmap.getImageInfo().size.height;
        float ratio = currentWidth / currentHeight;
        int outHeight = Math.round(outWidth / ratio);
        return getScaledBitmap(bitmap, outWidth, outHeight);
    }

    public static PixelMap getScaledBitmap(PixelMap bitmap, int outWidth, int outHeight) {
        float currentWidth = bitmap.getImageInfo().size.width;
        float currentHeight = bitmap.getImageInfo().size.height;
        Matrix scaleMatrix = new Matrix();
        scaleMatrix.postScale((float) outWidth / (float) currentWidth,
                (float) outHeight / (float) currentHeight);
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size.width = (int) currentWidth;
        initializationOptions.size.height = (int) currentHeight;
        return PixelMap.create(bitmap, initializationOptions);
    }

    public static int getMaxSize() {
        int maxSize = SIZE_DEFAULT;
        return maxSize;
    }

    public static void closeQuietly(Closeable closeable) {
        if (closeable == null) return;
        try {
            closeable.close();
        } catch (Throwable ignored) {
        }
    }

    public static void updateGalleryInfo(Context context, Uri uri) {
    }
}
